package com.fm.controller;

import com.fm.entity.Rule;
import com.fm.entity.RuleSql;
import com.fm.service.ProductFunctionService;
import com.fm.service.ProductService;
import com.fm.service.RuleService;
import com.fm.service.RuleSqlService;
import com.fm.utils.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/7/30 0030.
 */
@RestController
@RequestMapping("/api/rule")
public class RuleController extends MBaseController<Rule, RuleService>{

    @Autowired
    ProductService productService;
    @Autowired
    RuleSqlService ruleSqlService;
    @Autowired
    ProductFunctionService productFunctionService;

    @Override
    public Rule beforeList(Map t) {
        Rule rule = new Rule();
        rule.setUserId(SessionUtil.getLoginUserId());
        return rule;
    }

    @Override
    public void beforeInsert(Rule rule, HttpServletRequest request) {
        rule.setCreateTime(new Date());
        rule.setUserId(SessionUtil.getLoginUserId());
        rule.setStatus(1);
    }

    @Override
    public void afterSave(Rule rule, HttpServletRequest request) {
        ruleSqlService.deleteByRule(rule.getId());
        //先删除所有
        if (rule.getRuleSqlList()!=null) {
            for (RuleSql sql : rule.getRuleSqlList()) {
                sql.setRuleId(rule.getId());
                //获取字段类型
                //根据字段名和productID获取
                String name = sql.getType()==1?sql.getParam():sql.getMethodParam();
                Integer type =productFunctionService.getTypeByNameAndProductId(name, rule.getProductId());
                sql.setParamType(type);
                ruleSqlService.insert(sql);
            }
        }
    }

    @Override
    public void afterSelectOne(Rule rule) {
        RuleSql sql = new RuleSql();
        sql.setRuleId(rule.getId());
        List<RuleSql> ruleSqls = ruleSqlService.selectByExample(sql);
        rule.setRuleSqlList(ruleSqls);
    }

    //
//    @Override
//    public void afterList(Page<Equipment> page) {
//        for (Equipment equipment : page.getContent()) {
//            equipment.setProductName(productService.selectOneByExample(equipment.getProductId()).get().getName());
//        }
//    }
}
